package com.witmore.neutron.ai.web.tool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/tool")
public class ExcelToMarkdownController {

    private final ExcelToMarkdownService excelToMarkdownService;

    @Autowired
    private PdfToMarkdownService pdfToMarkdownService;

    public ExcelToMarkdownController(ExcelToMarkdownService excelToMarkdownService) {
        this.excelToMarkdownService = excelToMarkdownService;
    }

    @GetMapping("")
    public String showUploadForm(Model model) {
        return "upload-form";
    }

    @PostMapping("/convert")
    @ResponseBody
    public ResponseEntity<?> convertExcelToMarkdown(@RequestParam("files") MultipartFile[] files) {
        try {
            if (files == null || files.length == 0) {
                return ResponseEntity.badRequest().body(Map.of("error1", "请至少上传一个文件"));
            }
            // 最多上传10个
            if (files.length > 10) {
                return ResponseEntity.badRequest().body(Map.of("error1", "最多上传10个文件"));
            }
            List<Map<String, String>> results = new ArrayList<>();

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return ResponseEntity.badRequest()
                            .body(Map.of("error1", "文件不能为空"));
                }
                if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".xls")) {
                    return ResponseEntity.badRequest()
                            .body(Map.of("error1", "文件格式错误，请上传xls格式的文件"));
                }
                // Create temp file
                Path tempFile = Files.createTempFile("excel", ".xls");
                Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

                // Convert to markdown
                // 解析文件名称 杭州宇墨智联_202501.xls  公司名称_年份月份
                if (file.getOriginalFilename() == null || !file.getOriginalFilename().contains("_")) {
                    return ResponseEntity.badRequest()
                            .body(Map.of("error1", "文件名称格式错误，请使用 公司名称_年份月份_*.xls"));
                }
                String fileName = file.getOriginalFilename();
                String[] parts = fileName.split("_");
                String markdown = excelToMarkdownService.convertExcelToMarkdown(tempFile.toFile(), parts[0], Integer.parseInt(parts[1].substring(0, 4)), Integer.parseInt(parts[1].substring(4, 6)));
                // Delete temp file
                Files.deleteIfExists(tempFile);
                results.add(Map.of(
                        "fileName", file.getOriginalFilename(),
                        "content", markdown
                ));

            }

            return ResponseEntity.ok(Map.of("results", results));
        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of("error1", "文件处理错误: " + e.getMessage()));
        }
    }




    @PostMapping("/convert-pdf")
    public ResponseEntity<?> convertPdfToMarkdown(@RequestParam("files") MultipartFile[] files) {
        try {
            if (files == null || files.length == 0) {
                return ResponseEntity.badRequest().body(Map.of("error1", "请至少上传一个文件"));
            }
            // 最多上传10个
            if (files.length > 10) {
                return ResponseEntity.badRequest().body(Map.of("error1", "最多上传10个文件"));
            }
            List<Map<String, String>> results = new ArrayList<>();

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return ResponseEntity.badRequest()
                            .body(Map.of("error1", "文件不能为空"));
                }
                if (!file.getOriginalFilename().endsWith(".pdf")) {
                    return ResponseEntity.badRequest()
                            .body(Map.of("error1", "文件格式错误，请上传pdf格式的文件"));
                }
                // 创建临时文件
                Path tempFile = Files.createTempFile("pdf", ".pdf");
                Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
                // 转换PDF
                String markdown = pdfToMarkdownService.convertPdfToMarkdown(tempFile.toFile());

                // 删除临时文件
                Files.deleteIfExists(tempFile);
                results.add(Map.of(
                        "fileName", file.getOriginalFilename(),
                        "content", markdown
                ));
            }

            return ResponseEntity.ok(Map.of("results", results));


        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("Error processing PDF: " + e.getMessage());
        }
    }
}